package com.baidu.ueditor.upload;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.baidu.ueditor.PathFormat;
import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.FileType;
import com.baidu.ueditor.define.State;

public class BinaryUploader {

	public static final State save(HttpServletRequest request, Map<String, Object> conf) {

		try {
			// 解析器解析request的上下文
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());

			// 先判断request中是否包涵multipart类型的数据，
			if (!multipartResolver.isMultipart(request)) {
				return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
			}

			// 再将request中的数据转化成multipart类型的数据
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
			Iterator<?> iter = multiRequest.getFileNames();

			State state = new BaseState(true);
			while (iter.hasNext()) {
				MultipartFile file = multiRequest.getFile((String) iter.next());

				if (file == null) {
					return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
				}

				String savePath = (String) conf.get("savePath");

				String originFileName = file.getOriginalFilename();
				String suffix = FileType.getSuffixByFilename(originFileName);
				originFileName = originFileName.substring(0, originFileName.length() - suffix.length());
				savePath = savePath + suffix;
				long maxSize = ((Long) conf.get("maxSize")).longValue();
				if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
					return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
				}
				savePath = PathFormat.parse(savePath, originFileName);
				String physicalPath = (String) conf.get("rootPath") + savePath;
				File dest = new File(physicalPath);
				if (!dest.getParentFile().exists())
					dest.getParentFile().mkdirs();
				dest.createNewFile();

				file.transferTo(dest);

				state.putInfo("size", file.getSize());
				state.putInfo("title", file.getOriginalFilename());

				state.putInfo("url", PathFormat.format(savePath));
				state.putInfo("type", suffix);
				state.putInfo("original", originFileName + suffix);
			}

			return state;
			// } catch (FileUploadException e) {
			// return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
